<template>
    <a-row :gutter="10">
        <a-col :span="5">
            <a-card class="h-full" :bodyStyle="{ padding: '5px' }" :headerStyle="{ padding: '5px' }">

                <div class="mt-4" :style="{ height: tableHeight + 80 + 'px', overflow: 'auto' }">
                    <Scrollbar>
                        <a-form :model="searchData">

                            <a-form-item label="用户名">
                                <a-input v-model="searchData.sname"></a-input>
                            </a-form-item>
                            <a-form-item label="账号">
                                <a-input v-model="searchData.suser"></a-input>
                            </a-form-item>
                            <a-form-item label="手机号">
                                <a-input v-model="searchData.smobile"></a-input>
                            </a-form-item>
                            <a-form-item label="邮箱">
                                <a-input v-model="searchData.semail"></a-input>
                            </a-form-item>

                        </a-form>
                        <a-space>
                            <div>
                                <a-button style="width:100%" shape="round" type="primary" @click="doRefresh">查询
                                </a-button>
                            </div>
                            <a-button shape="round" type="primary" @click="addUser">添加用户</a-button>
                        </a-space>
                    </Scrollbar>

                </div>
            </a-card>
        </a-col>
        <a-col :span="19">
            <TableBody>
                <template #header>
                    <TableHeader ref="tableHeaderRef" :show-filter="false">
                    </TableHeader>
                </template>
                <template #default>
                    <a-table :bordered="false" :row-selection="{ selectedRowKeys }" :loading="tableLoading"
                        :data="dataList" :pagination="false" rowKey="sid" table-layout-fixed
                        :scroll="{ y: tableHeight, x: 1000 }" @selection-change="onSelectionChange">
                        <template #columns>
                            <a-table-column v-for="item of tableColumns" :key="item.key" :align="item.align"
                                :title="(item.title as string)" :width="item.width" :data-index="(item.key as string)"
                                :fixed="item.fixed">
                                <template v-if="item.key === 'index'" #cell="{ rowIndex }">
                                    {{ rowIndex + 1 }}
                                </template>
                                <template v-else-if="item.key === 'stime'" #cell="{record}">
                                    {{formatterkTime(record.stime)}}
                                </template>
                                <template v-else-if="item.key === 'actions'" #cell="{ record }">
                                    <a style="color:dodgerblue" @click="editUser(record)">修改</a>
                                    <a style="color:dodgerblue" @click="onDeleteItem(record)">删除</a>
                                </template>

                            </a-table-column>
                        </template>
                    </a-table>
                </template>
                <template #footer>
                    <TableFooter ref="tableFooterRef" :pagination="pagination" />
                </template>
            </TableBody>
            <ModalDialog ref="editModal" :title="modalTitle" @confirm="editOK">
                <template #content>
                    <a-form :model="searchData">
                        <a-form-item label="用户名">
                            <a-input v-model="editData.sname"></a-input>
                        </a-form-item>
                        <a-form-item label="账号">
                            <a-input v-model="editData.suser"></a-input>
                        </a-form-item>
                        <a-form-item label="手机号">
                            <a-input v-model="editData.smobile"></a-input>
                        </a-form-item>
                        <a-form-item label="邮箱">
                            <a-input v-model="editData.semail"></a-input>
                        </a-form-item>
                        <a-form-item label="公司部门">
                            <a-cascader v-model:model-value="gsList" :options="options" expand-trigger="hover"
                                :style="{ width: '320px' }"  popup-container="html"/>
                        </a-form-item>

                    </a-form>
                </template>
            </ModalDialog>
        </a-col>
    </a-row>
</template>

<script lang="ts">
import { post } from '@/api/http'

import {
    usePagination,
    useRowKey,
    useRowSelection,
    useTable,
    useTableColumn,
    useTableHeight,
} from '@/hooks/table'
import { Message, Modal } from '@arco-design/web-vue'
import { ModalDialogType } from '@/types/components'
import { defineComponent, getCurrentInstance, onMounted, ref, reactive, toRaw } from 'vue'
import md5 from 'js-md5'
import moment from 'moment'
import { slicing } from '@/utils/caseFrimAndSecRig'
export default defineComponent({
    name: 'ZZJG',
    setup() {
        const searchData = reactive({
            sname: "",
            suser: "",
            smobile: "",
            semail: ""
        });
        const editModal = ref<ModalDialogType | null>(null)
        const table = useTable()
        const rowKey = useRowKey('sid')
        const pagination = usePagination(doRefresh)
        const { selectedRowKeys, onSelectionChange } = useRowSelection()

        const tableColumns = useTableColumn([
            table.indexColumn,
            {
                title: "用户名",
                key: "sname",
                dataIndex: "sname",
                width: 150,
            },
            {
                title: "账号",
                key: "suser",
                dataIndex: "suser",
                width: 150,
            },
            {
                title: "手机号码",
                key: "smobile",
                dataIndex: "smobile",
                width: 150,
            },
            {
                title: "电子邮箱",
                key: "semail",
                dataIndex: "semail",
                width: 150,
            }, {
                title: "公司",
                key: "sfirm",
                dataIndex: "semail",
                width: 150,
            },
            {
                title: "部门",
                key: "sbumen",
                dataIndex: "semail",
                width: 150,
            },
            {
                title: "组",
                key: "szu",
                dataIndex: "semail",
                width: 150,
            },
            {
                title: "创建时间",
                key: "stime",
                dataIndex: "stime",
                width: 150
            },
            {
                title: "操作",
                key: "actions",
                fixed: "right",
                dataIndex: "actions",
                width: 150,
            }
        ]);

        function doRefresh() {
            post({
                url: "username/list",
                data: () => {
                    return {
                        ...(toRaw(searchData)),
                        page: pagination.page,
                        size: pagination.pageSize,
                    };
                },
            })
                .then((res) => {
                    table.handleSuccess(res.data.records);
                    pagination.setTotalSize(res.data.total);
                })
                .catch(console.log);
        }


        function onDeleteItems() {
            if (selectedRowKeys.value.length === 0) {
                Message.error('请选择要删除的数据')
                return
            }
            Modal.confirm({
                title: '提示',
                content: '确定要删除此数据吗？',
                cancelText: '取消',
                okText: '删除',
                onOk: () => {
                    Message.success(
                        '数据模拟删除成功，所选择的Keys为：' + JSON.stringify(selectedRowKeys.value)
                    )
                },
            })
        }
        function onDeleteItem(item: any) {
            Modal.confirm({
                title: '提示',
                content: '确定要删除此数据吗？',
                cancelText: '取消',
                okText: '删除',
                onOk: () => {
                    Message.success('数据删除成功')
                    table.dataList.splice(table.dataList.indexOf(item), 1)
                },
            })
        }


        const formatterkTime = (str: string): string => {
            let date = moment(new Date(str)).format("YYYY-MM-DD HH:mm:ss");
            return date;
        };
        const options = ref([])
        onMounted(async () => {
            table.tableHeight.value = await useTableHeight(getCurrentInstance())
            doRefresh()
            let res = await post({ url: 'firm/get' });
            options.value = res.data
        })

        const modalTitle = ref('')
        const editData = reactive({
            sid: '',
            sname: "",
            suser: "",
            smobile: "",
            semail: "",
        })

        const addUser = () => {
            editData.sid = ''
            editData.semail = ''
            editData.smobile = ''
            editData.sname = ''
            editData.suser = ''
            modalTitle.value = "新增用户"
            editModal.value?.toggle()
        }
        const gsList = ref<string[]>([])
        const editUser = (item: any) => {
            editData.sid = item.sid
            editData.semail = item.semail
            editData.smobile = item.smobile
            editData.sname = item.sname
            editData.suser = item.suser
            modalTitle.value = "修改用户"
            gsList.value = [item.sfirm, item.sbumen, item.szu]
            editModal.value?.toggle()
        }
        const editOK = () => {
            let gs = gsList.value[0] || ''
            let bm = gsList.value[1] || ''
            let zu = gsList.value[2] || ''
            if (modalTitle.value === '新增用户') {
                post({
                    url: "username/save",
                    data: {
                        ...toRaw(editData),
                        sfirm: gs,
                        sbumen: bm,
                        szu: zu,
                        "spass": md5('123456'),
                    }
                }).then(({ data, code }) => {
                    if (code === 200) {
                        Message.success('添加成功')
                    } else {
                        Message.error('添加失败')
                    }
                }).catch(() => {
                    Message.warning('网络错误')
                }).finally(() => {
                    editModal.value?.close()
                    doRefresh()
                })
            } else {
                post({
                    url: 'username/update',
                    data: {
                        ...toRaw(editData),
                        sfirm: gs,
                        sbumen: bm,
                        szu: zu
                    }
                }).then(({ code, data }) => {
                    if (code === 200) {
                        Message.success('修改成功')

                    } else {
                        Message.error('修改失败')
                    }

                }).catch(() => {
                    Message.warning('网络错误')
                }).finally(() => {
                    editModal.value?.close()
                })
            }
        }
        return {
            editOK,
            editData,
            gsList,
            modalTitle,
            options,
            editUser,
            editModal,
            addUser,
            formatterkTime,
            searchData,
            ...table,
            rowKey,
            selectedRowKeys,
            onSelectionChange,
            doRefresh,
            tableColumns,
            pagination,
            onDeleteItem,
            onDeleteItems,

        }
    },
})
</script>
